#!/bin/bash

echo "=========================================="
echo "Loft业务管理系统 - 环境初始化脚本"
echo "=========================================="

# 检查操作系统
if [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macOS"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="Linux"
else
    echo "不支持的操作系统: $OSTYPE"
    exit 1
fi

echo "检测到操作系统: $OS"

# 后端设置
echo ""
echo "=========================================="
echo "1. 初始化后端环境"
echo "=========================================="

cd backend || exit

if [ ! -d "venv" ]; then
    echo "创建Python虚拟环境..."
    python3 -m venv venv
else
    echo "虚拟环境已存在"
fi

echo "激活虚拟环境..."
source venv/bin/activate

echo "安装Python依赖..."
pip install -r requirements.txt

if [ ! -f ".env" ]; then
    echo "创建环境配置文件..."
    cp .env.example .env
    echo "请编辑 backend/.env 文件，配置数据库等信息"
else
    echo "环境配置文件已存在"
fi

echo ""
echo "后端环境初始化完成！"
echo "下一步："
echo "1. 编辑 backend/.env 配置文件"
echo "2. 创建数据库: createdb loft_db"
echo "3. 运行数据库迁移: cd backend && alembic upgrade head"
echo "4. 初始化数据: cd backend && python -m app.utils.init_db"
echo "5. 启动服务: cd backend && python run.py"

cd ..

# Flutter设置
echo ""
echo "=========================================="
echo "2. 初始化Flutter环境"
echo "=========================================="

if command -v flutter &> /dev/null; then
    echo "Flutter已安装"
    flutter --version
    
    cd flutter_app || exit
    echo "获取Flutter依赖..."
    flutter pub get
    echo "Flutter环境初始化完成！"
    cd ..
else
    echo "Flutter未安装，请先安装Flutter SDK"
    echo "macOS: brew install flutter"
    echo "或访问: https://flutter.dev/docs/get-started/install"
fi

# 微信小程序提示
echo ""
echo "=========================================="
echo "3. 微信小程序开发环境"
echo "=========================================="
echo "请手动完成以下步骤："
echo "1. 安装HBuilderX: https://www.dcloud.io/hbuilderx.html"
echo "2. 安装微信开发者工具: https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html"
echo "3. 在HBuilderX中打开 miniprogram 目录"
echo "4. 配置 manifest.json 中的微信小程序AppID"
echo "5. 配置 utils/config.js 中的后端API地址"

echo ""
echo "=========================================="
echo "安装完成！"
echo "=========================================="
echo ""
echo "快速启动："
echo "后端: cd backend && source venv/bin/activate && python run.py"
echo "Flutter: cd flutter_app && flutter run"
echo "小程序: 使用HBuilderX打开miniprogram目录"
echo ""
echo "文档："
echo "- 开发指南: docs/开发指南.md"
echo "- 部署文档: docs/deployment.md"
echo "- API文档: docs/API文档.md"
echo "- 或访问: http://localhost:8000/api/v1/docs"
echo ""

